package blue.mqtt4j.internal.client.net;

import blue.mqtt4j.client.MqttMessage;
import blue.mqtt4j.client.ProducerListener;
import blue.mqtt4j.internal.client.task.TaskExecutor;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * @author Jin Zheng
 * @since 1.0 2020-10-10
 */
public class NettyProducerListener implements ChannelFutureListener
{
	private final TaskExecutor executor;
	private final MqttMessage message;
	private final ProducerListener listener;
	private final boolean async;

	public NettyProducerListener(TaskExecutor executor, MqttMessage message, ProducerListener listener, boolean async)
	{
		this.executor = executor;
		this.message = message;
		this.listener = listener;
		this.async = async;
	}

	@Override
	public void operationComplete(ChannelFuture future) throws Exception
	{
		if (future.isSuccess())
		{
			if (async)
			{
				executor.execute(() -> listener.onComplete(message, null));
			}
			else
			{
				listener.onComplete(message, null);
			}
		}
		else
		{
			if (async)
			{
				executor.execute(() -> listener.onComplete(message, future.cause()));
			}
			else
			{
				listener.onComplete(message, future.cause());
			}
		}
	}
}
